<!--
 * @Author: 黑白灰01 3193273703@qq.com
 * @Date: 2025-02-12 10:17:51
 * @LastEditors: 黑白灰01 3193273703@qq.com
 * @LastEditTime: 2025-02-13 23:04:23
 * @FilePath: /hei_picture_web/src/page/space/_join/modal/JoinSlider.vue
 * @Description: 加入滑动组件
-->
<template>
  <div class="join-slider">
    <a-layout-sider>
      <a-menu
        v-model:selectedKeys="current"
        mode="inline"
        :items="menuItems"
        :loading="loading"
        @click="doMenuClick"
      />
    </a-layout-sider>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { listSpaceByPageUsingPost } from '@/api/spaceController'
import { listMyTeamSpaceUsingPost } from '@/api/spaceUserController'
import { SPACE_TYPE_ENUM } from '@/constants/spaceEnum'

const route = useRoute()
const router = useRouter()
const routeId = route?.params?.id
interface MenuItem {
  key: string
  label: string
  type?: 'group'
  children?: MenuItem[]
}
const current = ref<string[]>([])
const menuItems = ref<MenuItem[]>([
  {
    key: 'mySpace',
    label: '我的空间',
    type: 'group',
    children: [],
  },
  {
    key: 'joinSpace',
    label: '加入的团队',
    type: 'group',
    children: [],
  },
])
const loading = ref(false)
const loginUserStore = useLoginUserStore()
const userInfo = loginUserStore.loginUserInfo
const isLoaded = loginUserStore.isLoaded
const doMenuClick = ({ key }: { key: string }) => {
  console.log('doMenuClick', key)
  // Find which group contains the clicked item
  const group = menuItems.value.find((item) => item.children?.some((child) => child.key === key))
  console.log('group:', group?.key)
  current.value = [key]
  router.push(`/space/${key}/${group?.key}`)
}
router.afterEach((to) => {
  // console.log('afterEach', to)
  current.value = [to.params.id as string]
})
/**
 * @description: 验证用户是否登录
 */
const checkLoginUser = async () => {
  if (!userInfo?.userId) {
    message.warning('请先登录')
    router.replace('/login')
  }
}
/**
 * @description: 获取我的空间列表
 */
const getMySpaceList = async () => {
  loading.value = true
  try {
    const { data: res } = await listSpaceByPageUsingPost({
      pageSize: 1,
      current: 1,
      userId: userInfo?.userId ?? '',
      spaceType: SPACE_TYPE_ENUM.PRIVATE,
    })
    // console.log(res)
    if (res.code === 200 && res.data?.records) {
      const mySpaceItem = menuItems.value[0]
      if (mySpaceItem) {
        mySpaceItem.children = res.data.records.map((item) => ({
          key: item.id?.toString() ?? '',
          label: item.spaceName ?? '',
        }))
      }
    }
  } finally {
    loading.value = false
  }
}
const getJoinSpaceList = async () => {
  loading.value = true
  try {
    const { data: res } = await listMyTeamSpaceUsingPost()
    if (res.code === 200 && res.data) {
      // console.log(res.data)
      const joinSpaceItem = menuItems.value[1]
      if (joinSpaceItem) {
        joinSpaceItem.children = res.data.map((item) => ({
          key: item.space?.id?.toString() ?? '',
          label: item.space?.spaceName ?? '',
        }))
      }
    }
  } finally {
    loading.value = false
  }
}
const getCurrentItem = async () => {
  // 如果路由为 /space，跳转到第一个选项
  if (route.path === '/space') {
    await Promise.all([getMySpaceList(), getJoinSpaceList()])
    const firstSpace = menuItems.value[0].children?.[0]
    if (firstSpace) {
      current.value = [firstSpace.key]
      router.push(`/space/${firstSpace.key}/${menuItems.value[0].key}`)
    }
  } else if (routeId) {
    // 如果有具体的 routeId，则设置当前选中的空间
    current.value = [routeId.toString()]
  }
}
watchEffect(() => {
  getCurrentItem()
})
onMounted(() => {
  if (isLoaded) {
    checkLoginUser()
  }
  getMySpaceList()
  getJoinSpaceList()
})
</script>
